<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Canvas Viewport Rendering</title>
  </head>
  <body>
    <canvas id="myCanvas" width="300" height="300"></canvas>
    <script>
      const canvas = document.getElementById('myCanvas');
      const ctx = canvas.getContext('2d');

      // 背景图尺寸
      const bgWidth = 3000;
      const bgHeight = 3000;

      // 视窗尺寸和位置
      const viewWidth = 300;
      const viewHeight = 300;
      let viewX = 0; // 初始视窗位置
      let viewY = 0;

      // 加载背景图
      const img = new Image();
      // img.src = 'your-background-image-url.jpg'; // 替换为你的背景图路径
      // img.onload = function() {

      // };

      // 矩形列表，每个矩形有 x, y, width, height
      const rectangles = [
        { x: 50, y: 50, width: 100, height: 100, color: 'red' },
        { x: 1500, y: 1500, width: 200, height: 200, color: 'blue' },
        { x: 2500, y: 500, width: 150, height: 150, color: 'green' },
        // 添加更多矩形
      ];

      function drawScene() {
        // 清除画布
        ctx.clearRect(0, 0, viewWidth, viewHeight);

        // 渲染背景图的一部分
        ctx.drawImage(
          img,
          viewX,
          viewY,
          viewWidth,
          viewHeight,
          0,
          0,
          viewWidth,
          viewHeight
        );

        // 渲染在视窗中的矩形
        rectangles.forEach((rect) => {
          if (
            isRectangleInViewport(rect, viewX, viewY, viewWidth, viewHeight)
          ) {
            ctx.fillStyle = rect.color;
            ctx.fillRect(
              rect.x - viewX,
              rect.y - viewY,
              rect.width,
              rect.height
            );
          }
        });
      }

      function isRectangleInViewport(
        rect,
        viewX,
        viewY,
        viewWidth,
        viewHeight
      ) {
        return !(
          rect.x + rect.width < viewX ||
          rect.x > viewX + viewWidth ||
          rect.y + rect.height < viewY ||
          rect.y > viewY + viewHeight
        );
      }
      drawScene();

      // 示例：可以通过某种方式更新视窗位置（例如鼠标拖动）
      // 这里简单模拟更新视窗位置
      setTimeout(() => {
        viewX = 1350; // 更新视窗位置
        viewY = 1350;
        drawScene(); // 重新渲染
      }, 2000);
    </script>
  </body>
</html>
